import Axios from 'axios/index';
const instance = Axios.create();
let errorCallback=null;
//设置请求超时
instance.defaults.timeout = 3000;

instance.interceptors.request.use(
  function(config) {
    return config;
  },
  function(error) {
    return Promise.reject(error);
  },
);
//设置返回拦截器
instance.interceptors.response.use(
  function(response) {
    let data = response.data;
    let headers = response.headers;
    //业务正确为200；图片上传的为0，还未改过来，所以兼容两者
    headers.date = GMTToStr(headers.date);
    if (response.status == 200) {
      if (data.code == 200) {
        return {data, headers};
      }
    }
    return Promise.reject({data, headers});
  },
  function(error) {
    return Promise.reject({data: error, headers: null});
  },
);

function GMTToStr(time) {
  let date = new Date(time);
  let Str =
    date.getFullYear() +
    '-' +
    (date.getMonth() + 1) +
    '-' +
    date.getDate() +
    ' ' +
    date.getHours() +
    ':' +
    date.getMinutes() +
    ':' +
    date.getSeconds();
  return Str;
}

//设置token
export function setToken(token) {
  if (!token) {
    token = '';
  }
  instance.defaults.headers.common.Authorization = token;
}

//设置设备信息
export function setRequestFlag(flag = {}) {
  if (typeof flag !== 'object') {
    flag = JSON.parse(flag);
  }
  instance.defaults.headers.common['request-flag'] = encodeURI(
    JSON.stringify(flag),
  );;
}

export function setFlag(flag){
  instance.defaults.headers.common['request-flag'] = flag;
}

export function setBaseUrl(baseUrl){
  instance.defaults.baseURL = baseUrl
}

export function setErrorCallBack(callback) {
  errorCallback = callback
}


//http get
export function GET(url, params = {}) {
  let config = {
    method: 'get',
    url,
    params,
  };
  return request(config);
}

//htp post
export function POST(url, param = {}) {
  let config = {
    method: 'post',
    url,
    data: param,
  };
  return request(config);
}

//http put
export function PUT(url, param = null) {
  let config = {
    method: 'put',
    url,
    data: param,
  };
  return request(config);
}

//http delete
export function DELETE(url, param = null) {
  let config = {
    method: 'delete',
    url,
    data: param,
  };
  return request(config);
}

//统一请求
function request(config) {
  console.log('请求参数', config);
  return instance(config)
    .then(res => {
      return handleResponse(config.url, res, null);
    })
    .catch(error => {
      return handleResponse(config.url, null, error);
    });
}

//处理请求返回
function handleResponse(url, res, error) {
  if (__DEV__) {
    if (error) {
      console.log(`${url} 错误：`, error);
    } else {
      console.log(`${url} 数据：`, res.data);
    }
  } else {
    //线上的话 转换成str
    if (error) {
      console.log(`${url} 错误：`, JSON.stringify(error));
    } else {
      console.log(`${url} 数据：`, JSON.stringify(res.data));
    }
  }
  let handleError = null;
  if (error) {
    let {data, headers} = error;
    error = data;
    if (error.code) {
      //业务逻辑报错
      handleError = error;
    } else {
      //其他
      handleError = {};
      if (error.response) {
        //服务器响应了错误
        const {error: msg, status, path} = error.response.data;
        handleError.code = status;
        handleError.msg = msg;
        handleError.desc = '请求出错，服务器响应了错误';
        handleError.path = path;
      } else if (error.request) {
        //请求了，但是没有响应

        handleError.code = '-1';
        handleError.msg = error.message;
        handleError.desc = '没有收到服务器的响应';
        handleError.path = url;
      } else {
        //其它
        // Something happened in setting up the request that triggered an Error
        handleError.code = '-2';
        handleError.msg = '请求发起失败';
        handleError.desc =
          'Something happened in setting up the request that triggered an Error';
        handleError.path = url;
      }
    }
    if(errorCallback){
      errorCallback(handleError)
    }
    return {res: null, error: handleError};
  } else {
    let headers = res.headers;
    res = res.data;
    let data = res ? res.data : res;
    return {res: data, error: handleError, headers};
  }
}

